package com.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.controller.reqdto.ElectricityReportParam;
import com.controller.reqdto.HeartReportParam;
import com.controller.reqdto.heartReportContentParam;
import com.controller.respdto.group.GroupMsgResp;
import com.controller.template.ResultHelper;
import com.controller.template.ResultInfo;
import com.enums.CommonEnum;
import com.repository.mapper.GroupMsgMapper;
import com.repository.mapper.PcGroupRelationshipMapper;
import com.repository.mapper.PcMessageMapper;
import com.repository.po.GroupMsg;
import com.repository.po.PcGroupRelationship;
import com.repository.po.PcMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;


/**
 * @author ruiwen
 */
@RestController
@Api(tags = "open模块")
@CrossOrigin
@RequestMapping("/open")
@Slf4j
public class openController extends ResultHelper {

    @Resource
    PcGroupRelationshipMapper pcGroupRelationshipMapper;

    @Resource
    GroupMsgMapper groupMsgMapper;
    @Resource
    PcMessageMapper pcMessageMapper;

    /**
     * 心跳上报
     *
     * @param heartReportParam
     * @return
     */
    @ApiOperation("心跳上报")
    @PostMapping("/heartReport")
    public ResultInfo heartReport(@RequestBody HeartReportParam heartReportParam) {
        log.info("心跳上报参数：{}", heartReportParam);
        List<heartReportContentParam> heartReportContentParamList = heartReportParam.getHeartReportContentParamList();
        if (Objects.isNull(heartReportContentParamList) || heartReportContentParamList.size() == 0) {
            return failResultInfo(500, "上报设备信息不能为空");
        }
        for (heartReportContentParam heartReportContentParam : heartReportContentParamList) {
            PcMessage pcMessage = pcMessageMapper.selectOne(new QueryWrapper<PcMessage>().eq("pc_unique_key", heartReportContentParam.getDeviceNo()));
            if (Objects.isNull(pcMessage)) {
                continue;
            }
            PcMessage updatePcMessage = new PcMessage();
            updatePcMessage.setId(pcMessage.getId());
            updatePcMessage.setContentProgress(heartReportContentParam.getProgress().multiply(new BigDecimal(100)));
            updatePcMessage.setUpdateTime(new Date());
            pcMessageMapper.updateById(updatePcMessage);
            log.info("心跳上报设备信息：{}", heartReportContentParam);
            //根据pc查时间最新的组
            PcGroupRelationship pcGroupRelationship1 = pcGroupRelationshipMapper.selectOne(new QueryWrapper<PcGroupRelationship>().eq("pc_id", pcMessage.getId()).orderByDesc("create_time").last("limit 1"));
            if (Objects.isNull(pcGroupRelationship1)) {
                continue;
            }
            GroupMsg groupMsg = groupMsgMapper.selectById(pcGroupRelationship1.getGroupId());
            if (Objects.isNull(groupMsg)||! Objects.equals(groupMsg.getGroupStatus(), CommonEnum.GROUP_RUNNING.getCode())) {
                continue;
            }
            List<PcGroupRelationship> pcGroupRelationships = pcGroupRelationshipMapper.selectList(new QueryWrapper<PcGroupRelationship>().eq("group_id", groupMsg.getId()).eq("pc_id", pcMessage.getId()));
            BigDecimal progress = new BigDecimal(0);
            for (PcGroupRelationship pcGroupRelationship : pcGroupRelationships) {
                PcMessage pcMessage1 = pcMessageMapper.selectById(pcGroupRelationship.getPcId());
                if (Objects.nonNull(pcMessage1)) {
                    progress = progress.add(pcMessage1.getContentProgress());
                }
            }
            progress = progress.divide(new BigDecimal(pcGroupRelationships.size()), 2, BigDecimal.ROUND_HALF_UP);
            groupMsg.setContentProgress(progress);
            groupMsgMapper.updateById(groupMsg);
            log.info("心跳上报进度更新完成：{}", groupMsg);
        }

        if (Objects.nonNull(heartReportParam.getGroupId())){

        }
        return successResultInfo("心跳上报成功");

    }

    /**
     * 获取群组信息
     *
     * @param macId
     * @return
     */
    @ApiOperation("获取群组信息")
    @GetMapping("/getGroupMsg/{macId}")
    public ResultInfo getGroupMsg(@PathVariable("macId") String macId) {
        log.info("获取群组信息参数：{}", macId);

        GroupMsgResp groupMsgResp = new GroupMsgResp();
        PcMessage pcMessage = pcMessageMapper.selectOne(new QueryWrapper<PcMessage>().eq("pc_unique_key", macId));
        if (Objects.isNull(pcMessage)) {
            return failResultInfo(500, "未找到对应的s宿主机");
        }
        groupMsgResp.setNickName(pcMessage.getPcName());
//
//        GroupMsg groupMsg = groupMsgMapper.selectOne(new QueryWrapper<GroupMsg>().eq("group_status", 1));
//        PcGroupRelationship pcGroupRelationship = pcGroupRelationshipMapper.selectOne(new QueryWrapper<PcGroupRelationship>().eq("pc_id", pcMessage.getId()).eq("group_id", groupMsg.getId()));
        PcGroupRelationship pcGroupRelationship = pcGroupRelationshipMapper.selectOne(new QueryWrapper<PcGroupRelationship>().eq("pc_id", pcMessage.getId()).orderByDesc("create_time").last("limit 1"));
        List<PcGroupRelationship> pcGroupRelationships = pcGroupRelationshipMapper.selectList(new QueryWrapper<PcGroupRelationship>().eq("group_id", pcGroupRelationship.getGroupId()));
        if (pcGroupRelationships.size() == 0) {
            throw new RuntimeException("分组不存在");
        }
        //取分组信息的第一个
        if (Objects.equals(pcGroupRelationships.get(0).getPcId(),pcMessage.getId())){
            groupMsgResp.setIsFirst(true);
        }
        //打印分组信息
        log.info("分组信息：{}", pcGroupRelationships);
        if (Objects.isNull(pcGroupRelationship)) {
            return failResultInfo(500, "未找到对应的群组");
        }
        groupMsgResp.setGroupId(pcGroupRelationship.getGroupId());


        return successResultInfo(groupMsgResp);
    }

    /**
     * 心跳上报
     *
     * @param electricityReportParam
     * @return
     */
    @ApiOperation("电量上报")
    @PostMapping("/electricityReport")
    public ResultInfo heartReport(@RequestBody ElectricityReportParam electricityReportParam) {
        log.info("电量上报参数：{}", electricityReportParam);
        PcMessage pcMessage = pcMessageMapper.selectOne(new QueryWrapper<PcMessage>().eq("pc_unique_key", electricityReportParam.getMac()));
        if (Objects.isNull(pcMessage)) {
            return failResultInfo(500, "未找到对应的宿主机");
        }
        PcMessage updatePcMessage = new PcMessage();
        updatePcMessage.setId(pcMessage.getId());
        updatePcMessage.setElectricity(Integer.parseInt(electricityReportParam.getElectricity()));
        updatePcMessage.setUpdateTime(new Date());
        pcMessageMapper.updateById(updatePcMessage);
        return successResultInfo("电量上报成功");

    }

}
